package cn.yoyo.controller.fore;

import cn.yoyo.entity.LargeFile;
import cn.yoyo.tools.RespJson;
import cn.yoyo.entity.SysUser;
import cn.yoyo.service.LargeFileService;
import cn.yoyo.service.UserService;
import cn.yoyo.tools.GetUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

@RestController
public class ForeUserController {
    @Autowired
    UserService userService;
    @Autowired
    LargeFileService largeFileService;

    @RequestMapping("/api/public/addUser")
    public Map<String, Object> add(SysUser user, @RequestParam("picture") MultipartFile file) {
        if (userService.addUser(user, file) > 0) {
            if (file != null && file.getSize() > 0) {
                try {
                    largeFileService.add(new LargeFile(user.getImg(), file.getOriginalFilename(), file.getBytes()));
                } catch (Exception e) {
                    System.err.println(e.getMessage());
                }
            }
        }
        return null;
    }

    @RequestMapping("/api/fore/user/updatePassword")
    public Map<String, Object> updatePassword(String password) {
        System.out.println(password);
        if (password == null || "".equals(password)) {
            return RespJson.pack(400, "输入密码为空,无法修改", null);
        }
        userService.updatePassword(password);
        return RespJson.pack(200, "修改密码成功,请重新登录", null);
    }

    @RequestMapping("/api/fore/user/updateImg")
    public Map<String, Object> updateImg(@RequestParam("img") MultipartFile file) {
        System.out.println(file.getOriginalFilename());
        if (file == null || file.getSize() <= 0) {
            return RespJson.pack(400, "未选择图片，修改失败", null);
        }
        userService.updateImg(file);
        return RespJson.pack(200, "修改头像成功", GetUser.getUser());
    }

    @RequestMapping("/api/fore/user/updateInfo")
    public Map<String, Object> updateInfo(@RequestParam("nickname") String nickename, String phone) {
        System.out.println("nickname=" + nickename + "..." + "phone=" + phone);
        if (nickename == null || phone == null
                && "".equals(nickename) || "".equals(phone)) {
            return RespJson.pack(400, "值不能为空，修改失败", null);
        }
        userService.updateInfo(nickename, phone);
        return RespJson.pack(200, "修改成功", GetUser.getUser());
    }
}
